package algorithmcase;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

public class Case1 {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9,10));
        Integer number = new Random().nextInt(10);
        System.out.println(number);
        ArrayList<Integer> indexList = basicSearch(list, number);
        System.out.println(indexList);
        System.out.println(binarySearch(list,number));
    }
    private static ArrayList<Integer> basicSearch(ArrayList<Integer> list,int target) {
        ArrayList<Integer> indexList = new ArrayList<Integer>();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) == target) {
                indexList.add(i);
            }
        }
        return indexList;
    }
    //二分查找
    private static int binarySearch(ArrayList<Integer> list,int target) {
        int low = 0;
        int high = list.size() - 1;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (list.get(mid) == target) {
                return mid;
            } else if (list.get(mid) > target) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return -1;
    }
}
